﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel.Dispatcher;
using System.Diagnostics.Contracts;
using System.ServiceModel;
using System.ServiceModel.Channels;

namespace YasharEl.Infrastructure.ObjectFactory.ServiceModel
{
    public class DependencyContainerInstanceProvider : IInstanceProvider
    {
        #region ReadOnly Fields

        private readonly Type _serviceType;
        private readonly IDependencyResolver resolver;
        private readonly IDependencyRegistrar registrar;

        #endregion

        #region Properties

        public IDependencyResolver DependencyResolver
        {
            get { return resolver; }
        }

        #endregion

        #region Constructors

        public DependencyContainerInstanceProvider(Type serviceType, IDependencyResolver resolver, IDependencyRegistrar registrar)
        {
            Contract.Requires<ArgumentNullException>(serviceType != null, "serviceType could not be null.");
            Contract.Requires<ArgumentNullException>(resolver != null, "resolver could not be null.");
            Contract.Requires<ArgumentNullException>(registrar != null, "registrar could not be null.");

            _serviceType = serviceType;
            this.resolver = resolver;
            this.registrar = registrar;
        }

        #endregion

        #region IInstanceProvider Implementations

        public object GetInstance(InstanceContext instanceContext, Message message)
        {
            return resolver.Resolve(_serviceType);
        }

        public object GetInstance(InstanceContext instanceContext)
        {
            return GetInstance(instanceContext, null);
        }

        /// <summary>
        /// Called when an System.ServiceModel.InstanceContext object recycles a service object.
        /// </summary>
        /// <param name="instanceContext">The service's instance context.</param>
        /// <param name="instance">The service object to be recycled.</param>
        public void ReleaseInstance(InstanceContext instanceContext, object instance)
        {

        }

        #endregion
    }
}
